package com.pic4493.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

//import javax.imageio.ImageIO;

import com.pic4493.app.R;
import com.ppcodes.imageloader.utils.StorageUtils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class UtiImage
{
   public static final String IMAGE_HEAD_NAME = "faceImage.jpg";
   public static final String IMAGE_WALLPAPER = "wallpaper.jpg";
   public static final int LOCAL_IMAGE_REQUEST_CODE = 0;
   public static final int CAMERA_REQUEST_CODE = 1;
   public static final int RESULT_REQUEST_CODE = 2;

   public static final int BUFF_SIZE = 2048;
   public static final String DEFAULT_ENCODING = "utf-8";

   /**
    * 裁剪图片方法
    * 
    * @param activity
    * @param uri
    * @param outputX
    * @param outPutY
    * @param requestCode
    */
   public static void cropPhoto(Activity activity, Uri uri, int outputX, int outPutY, int requestCode)
   {
	  Intent intent = new Intent("com.android.camera.action.CROP");
	  intent.setDataAndType(uri, "image/*");
	  // 设置裁剪
	  intent.putExtra("crop", "true");
	  // aspectX aspectY 是宽高的比例
	  intent.putExtra("aspectX", 1);
	  intent.putExtra("aspectY", 1);
	  // outputX outputY 是裁剪图片宽高
	  intent.putExtra("outputX", outputX);
	  intent.putExtra("outputY", outPutY);
	  intent.putExtra("return-data", true);
	  intent.putExtra("scale", true);
	  intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	  intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	  // intent.putExtra("noFaceDetection", true); // no face detectio
	  activity.startActivityForResult(intent, requestCode);
   }

   public static void setFaceImage(final Activity activity)
   {
	  String[] items = new String[] { "选择本地图片", "拍照" };
	  UtiDialog.getInstance().ShowItemsDialogWithTitle(activity, items, "设置头像", new DialogInterface.OnClickListener()
	  {
		 @Override
		 public void onClick(DialogInterface dialog, int which)
		 {
			switch (which)
			{
			   case 0:
				  Intent intentFromGallery = new Intent();
				  intentFromGallery.setType("image/*"); // 设置文件类型
				  intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
				  activity.startActivityForResult(intentFromGallery, LOCAL_IMAGE_REQUEST_CODE);
				  break;
			   case 1:
				  Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				  // 判断存储卡是否可以用，可用进行存储
				  if (UtiFile.hasSdcard())
				  {
					 intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(StorageUtils.getCacheDirectory(activity), IMAGE_HEAD_NAME)));
				  }
				  activity.startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
				  break;
			}
		 }
	  });
   }

   public static String readFileToString(File file, String encoding)
   {
	  try
	  {
		 byte[] buffer = new byte[BUFF_SIZE];
		 if (encoding == null || encoding.length() == 0)
			encoding = DEFAULT_ENCODING;

		 StringBuffer content = new StringBuffer();

		 FileInputStream fis = new FileInputStream(file);

		 int bytesRead = 0;
		 while ((bytesRead = fis.read(buffer)) != -1)
		 {
			content.append(new String(buffer, 0, bytesRead, encoding));
		 }
		 fis.close();
		 return content.toString();

	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiImage_readFileToString(filePath, encoding) " + e);
	  }
	  return encoding;
   }

   public static byte[] readFileToByte(File file, String encoding)
   {
	  byte[] buffer = new byte[BUFF_SIZE];
	  try
	  {

		 if (encoding == null || encoding.length() == 0)
			encoding = DEFAULT_ENCODING;

		 StringBuffer content = new StringBuffer();

		 FileInputStream fis = new FileInputStream(file);

		 int bytesRead = 0;
		 while ((bytesRead = fis.read(buffer)) != -1)
			content.append(new String(buffer, 0, bytesRead, encoding));

		 fis.close();
		 // return content.toString();
		 // return buffe;
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiImage_readFileToString(filePath, encoding) " + e);
	  }
	  return buffer;
	  // return encoding;
   }

   // public static byte[] toByteArray(File imageFile)
   // {
   // BufferedImage img = null;
   // try
   // {
   // img = ImageIO.read(imageFile);
   // }
   // catch (IOException e1)
   // {
   // e1.printStackTrace();
   // }
   // ByteArrayOutputStream buf = new ByteArrayOutputStream((int)
   // imageFile.length());
   // try
   // {
   // ImageIO.write(img, "jpg", buf);
   // }
   // catch (Exception e)
   // {
   // e.printStackTrace();
   // return null;
   // }
   // return buf.toByteArray();
   // }

   public static void saveFaceBitmap(Bitmap mBitmap)
   {
	  File f = new File(UtiFile.getExternalCacheDir(),IMAGE_HEAD_NAME);
	  try
	  {
		 if (f.exists())
		 {
			f.delete();
		 }
		 f.createNewFile();
		 FileOutputStream fOut = null;
		 fOut = new FileOutputStream(f);
		 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
		 fOut.flush();
		 fOut.close();
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiFile_saveMyBitmap(bitName, mBitmap) " + e);
	  }
   }

   /**
    * 反序列化bitmap
    * 
    * @param data
    * @return
    */
   public static Bitmap getBitmap(byte[] data)
   {
	  return BitmapFactory.decodeByteArray(data, 0, data.length);
   }

   /**
    * 序列化bitmap
    * 
    * @param bitmap
    * @return
    */
   public static byte[] getBytes(Bitmap bitmap)
   {
	  ByteArrayOutputStream baops = new ByteArrayOutputStream();
	  bitmap.compress(CompressFormat.JPEG, 0, baops);
	  return baops.toByteArray();
   }

   /**
    * Get image from newwork
    * 
    * @param url
    *           The path of image
    * @return InputStream
    * @throws Exception
    */
   public static Bitmap getImage(String _url)
   {
	  try
	  {
		 URL url = new URL(_url);
		 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		 conn.setConnectTimeout(5 * 1000);
		 conn.setRequestMethod("GET");
		 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
		 {
			return BitmapFactory.decodeStream(conn.getInputStream());
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiImage_getImageStream(_url) " + e);
	  }
	  return null;
   }

   public static void saveWallPaper(Bitmap mBitmap)
   {
	  File f = new File(UtiFile.getExternalWallPaperDir(),IMAGE_WALLPAPER);
	  try
	  {
		 if (f.exists())
		 {
			f.delete();
		 }
		 f.createNewFile();
		 FileOutputStream fOut = null;
		 fOut = new FileOutputStream(f);
		 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
		 fOut.flush();
		 fOut.close();
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiFile_saveWallPaper(bitName, mBitmap) " + e);
	  }
   }

   /**
    * 
    * @param context
    * @return
    */
   public static Bitmap loadWallPaper(Context context)
   {
	  File f = new File(UtiFile.getExternalWallPaperDir(),IMAGE_WALLPAPER);
	  try
	  {
		 if (!f.exists())
		 {
			return ((BitmapDrawable) context.getResources().getDrawable(R.drawable.wallpaper_default)).getBitmap();
		 }
		 else
		 {
            return BitmapFactory.decodeFile(f.getAbsolutePath());
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiFile_saveWallPaper(bitName, mBitmap) " + e);
	  }
	  return null;
   }

   /**
    * 保存文件
    * 
    * @param bm
    * @param fileName
    * @throws IOException
    */
   public static void saveBitmap(Bitmap bm, String path, String fileName)
   {
	  try
	  {
		 File dirFile = new File(path);
		 if (!dirFile.exists())
		 {
			dirFile.mkdir();
		 }
		 File myCaptureFile = new File(path + fileName);
		 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		 bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		 bos.flush();
		 bos.close();
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiImage_saveFile(bm, fileName) " + e);
	  }
   }

}
